package com.joker.microstoremanager.controller;

import com.joker.common.model.JokerResponse;
import com.joker.microstoremanager.context.UserContext;
import com.joker.microstoremanager.model.DataTablePage;
import com.joker.microstoremanager.model.MicroShop;
import com.joker.microstoremanager.model.Tag;
import com.joker.microstoremanager.service.GoodsService;
import com.joker.microstoremanager.service.TagService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

@org.springframework.web.bind.annotation.RestController
@RequestMapping("/home")
public class IndexRestController {
    @Resource
    private GoodsService service;
    @Resource
    private TagService tagService;

    @GetMapping("recategory")
    public JokerResponse<String> recategory(){
        MicroShop user = (MicroShop) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        service.recategory(user);
        return new JokerResponse<>("重新分类完成！");
    }

    @GetMapping("tagData")
    public DataTablePage<Tag> tagData(String tagName,@RequestParam(value = "start", defaultValue = "0") Integer page,
                                      @RequestParam(value = "length", defaultValue = "10") Integer length){
        Pageable request = new PageRequest(page/length,length);
        MicroShop user = UserContext.getUser();
        Page<Tag> tagPage = tagService.findByShopIdAndName(user.getId(),tagName,request);
        return new DataTablePage<>(tagPage);
    }

    @PostMapping(value = "tagAdd")
    public JokerResponse<String> tagAdd(Tag tag){
        MicroShop user = UserContext.getUser();
        JokerResponse<String> result = new JokerResponse<>();
        if(null != tagService.findByShopIdAndName(user.getId(), tag.getName())){
            result.setMessage("该标签已存在,请勿重复添加！");
            result.setCode(403);
            return result;
        }
        tag.setShop(user);
        tagService.save(tag);
        result.setMessage("标签添加成功！");
        return result;
    }
}
